<?php
/*
 * Data Explorer: External Source Driver
 *      "query.php"
 *
 * last modified: 3/25/11
 * author: James Duran
 *
 * description: provides an interface for querying external
 *              data sources, based on the get input
 *              referring to the dataset name and query string.
 *
 * comments: n/a
 */
require_once 'mysqlDriver.php';

// retrieve the post values.
// right now post is being used because get places a
// character limit on requests.
$ds = $_GET["ds"];
$code = $_GET["q"];

// queryAirports:
//
// queries the the database and returns a json array of the
// database results.
function queryAirports($str) {
  $_array = array();
  $_result = sqlSelect($str);

  while($_row = mysql_fetch_assoc($_result)) {
    $_arrayRow['value'] = $_row['code'] .
    ', ' . $_row['name'] .
    ', ' . $_row['city'] .
    ', ' . $_row['state'];

    $_arrayRow['id']['latitude'] = $_row['latitude'];
    $_arrayRow['id']['longitude'] = $_row['longitude'];
    array_push($_array, $_arrayRow);
  }
  mysql_free_result($_result);
  echo json_encode($_array);
}

// queryUSGS:
//
// queries the database and returns a json array of the most
// relevant USGS entry based off a given site id.
function queryUSGS($str) {
  $_array = array();
  $_result = sqlSelect($str);

  while($_row = mysql_fetch_assoc($_result)) {
    $_arrayRow["value"] = $_row["site_name"];
    $_arrayRow["id"]["latitude"] = $_row["latitude"];
    $_arrayRow["id"]["longitude"] = $_row["longitude"];
    $_arrayRow["id"]["site_id"] = $_row["site_id"];
    $_arrayRow["id"]["huc_code"] = $_row["huc_code"];
    array_push($_array, $_arrayRow);
  }
  mysql_free_result($_result);
  echo json_encode($_array);
}

// if/else/switch statement which chooses action
// based on the dataset 'ds' name.
if($ds == "faaws")
  queryAirports("select * from `faa_airport_loc_list` where `code` like '%" .
		$code . "%' limit 1");
elseif($ds == "usgs") {
  queryUSGS("select * from " .
	    "`usgs_site_loc_list` where `site_id` like '%" . $code . "%' limit 1");
}
else {
}